package com.bom.boot.controller;

import cn.hutool.core.io.FileUtil;
import com.bom.boot.core.Result;
import com.bom.boot.facade.dto.EmptyDTO;
import com.bom.boot.facade.dto.UtilDockerJavaDTO;
import com.bom.boot.facade.dto.UtilRabbitmqAddDTO;
import com.bom.boot.facade.vo.UtilDockerJavaVO;
import com.bom.boot.facade.vo.UtilRabbitmqAddVO;
import com.bom.boot.facade.vo.UtilRabbitmqMqttVO;
import com.bom.boot.service.UtilService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@Controller
@RequestMapping("util")
@AllArgsConstructor
@Schema(description = "部署工具")
@Slf4j
public class UtilController {

    private final UtilService utilService;

    @PostMapping("rabbitmq/add")
    @ResponseBody
    @Operation(summary = "docker rabbitmq 添加用户", tags = {"rabbitmq"})
    public Result<UtilRabbitmqAddVO> rabbitmqAdd(@RequestBody UtilRabbitmqAddDTO dto) {
        return utilService.rabbitmqAdd(dto);
    }

    @PostMapping("rabbitmq/mqtt")
    @ResponseBody
    @Operation(summary = "docker rabbitmq 启动mqtt", tags = {"rabbitmq"})
    public Result<UtilRabbitmqMqttVO> rabbitmqMqtt(@RequestBody EmptyDTO dto) {
        return utilService.rabbitmqMqtt(dto);
    }

    @PostMapping("java")
    @ResponseBody
    @Operation(summary = "docker java 服务", tags = {"java"})
    public void dockerJava(@RequestBody UtilDockerJavaDTO dto, HttpServletResponse response) {
        UtilDockerJavaVO vo = utilService.dockerJava(dto);
        try (
                OutputStream out = response.getOutputStream();
        ) {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(FileUtil.getName(vo.getZipPath()), "UTF-8"));
            out.write(FileUtil.readBytes(vo.getZipPath()));
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            FileUtil.del(vo.getZipPath());
        }
    }
}
